package user

import (
	"context"

	"mall/common/globalkey"
	"mall/common/resultx"
	"mall/service/backend/common/i18n"
	"mall/service/user/rpc/internal/svc"
	"mall/service/user/rpc/types/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type LogoutLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLogoutLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LogoutLogic {
	return &LogoutLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LogoutLogic) Logout(in *user.LogoutReq) (*user.BaseResp, error) {
	if in.UserId == nil || *in.UserId == 0 {
		return nil, resultx.StatusError(resultx.USER_ID_REQUIRED, "")
	}

	// 查询后修改
	curUser, err := l.svcCtx.CurrentUser.FindOneNoCache(l.ctx, nil, *in.UserId)
	if err != nil {
		return nil, err
	}

	var changed bool
	if in.Cancel != nil && *in.Cancel > 0 { // 注销
		if curUser.UserStatus != uint16(globalkey.StatusExpired) {
			curUser.UserStatus = uint16(globalkey.StatusExpired)
			changed = true
		}
	} else {
		if curUser.UserStatus != uint16(globalkey.StatusAsGuest) {
			curUser.UserStatus = uint16(globalkey.StatusAsGuest)
			changed = true
		}
	}

	if changed {
		err = l.svcCtx.CurrentUser.Update(l.ctx, nil, curUser, nil)
		if err != nil {
			return nil, err
		}
	}

	return &user.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}
